qui(
    function (require, exports, module) {
        VODCom.AutoTitle = {
            AUTO_TITLE_QUERY_FLAG: 0,
            AUTO_TITLE_FLAG: 0,
            AUTO_TITLE_ORIGIN: null,
            USER_TITLE_SELECT: -1,
            parentInstance: null,
            contentInstance: null,
            lastQueryKey: null,
            dataCenter: [],
            CropInstance: null,
            options: null,
            stopQuery: false,
            clearData: function () {
                this.AUTO_TITLE_QUERY_FLAG = 0;
                this.AUTO_TITLE_FLAG = 0;
                this.AUTO_TITLE_ORIGIN = null;
                $("div.hint_title").remove();
                this.dataCenter = [];
                this.lastQueryKey = null;
            },
            initAutoTitleDlg: function (options) {
                var self = this;
                self.options = options;
                self.getParentDiv().dialog({
                    title: "标题自动识别",
                    resizable: false,
                    dialogClass: 'alert',
                    autoOpen: false,
                    width: 820,
                    modal: true,
                    open: function () {
                        if ($("label[name=label_sel_auto_title]").length > 0) {
                            if ($("label.title_selected").length == 0) {
                                $("label[name=label_sel_auto_title]:eq(0)").click();
                            }
                        }
                    },
                    close: function () {
                        console.log(" 标题自动识别 关闭");
                        $("#auto_title_alterDiv").hide();
                        self.options["body"].append($("#auto_title_alterDiv"));

                    }
                })
                self.CropInstance = $.Jcrop("#auto_image", {
                    onChange: self.doCropChange,
                    onSelect: self.doCropSelect,
                    boxHeight: 450,
                    minSelect: [10, 10]
                })

                $("button[name=auto_title-ok]").on("click", function (event) {
                    self.getParentDiv().dialog("close");
                    if (self.getContentDiv().find("input[type=radio]:checked").length > 0) {
                        var selTitle = self.getContentDiv().find("input[type=radio]:checked").parent().next().text()
                        $("input[name=videoName]").val(selTitle.trim());
                        $("input[name=videoName]").change();
                        self.AUTO_TITLE_QUERY_FLAG = 1;
                        self.AUTO_TITLE_FLAG = 1;
                        self.AUTO_TITLE_ORIGIN = self.dataCenter[  parseInt(self.getContentDiv().find("input[type=radio]:checked").val()) - 1].key.trim();
                        self.getOptionsEntity("config").OCR_TITLE_FLAG = 0;
                    }
                })
                $("button[name=auto_title-cancel]").on("click", function (event) {
                    self.AUTO_TITLE_QUERY_FLAG = 0;
                    self.getParentDiv().dialog("close");
                })
            },

            getParentDiv: function () {
                if (this.parentInstance == null) {
                    this.parentInstance = $("#auto_title-dlg");
                }
                return this.parentInstance
            },
            getContentDiv: function () {
                if (this.contentInstance == null) {
                    this.contentInstance = $("#auto_title-dlg_content");
                }
                return this.contentInstance
            },
            bindEvent: function () {
                var self = this;
                $("button[name=btn_get_auto_title]").bind("click", function (event) {
                    self.getAutoTitleList();
                })
                self.getContentDiv().delegate("label[name=label_sel_auto_title]", "click", function (event) {
                    $(event.currentTarget).parent().find("input[name=auto_selected_title]").click();
                })
                var alterDiv = $("#auto_title_alterDiv");
                self.getContentDiv().delegate("input[name=auto_selected_title]", "click", function (event) {
                    var brother = $(event.currentTarget).parent().next();
                    alterDiv.find("input[name=image_auto_title]").val(brother.text());
                    alterDiv.find("input[name=image_auto_title]").change();
                    alterDiv.show();
                    brother.parent().append(alterDiv);
                    self.loadDataImage(parseInt($(event.currentTarget).val()) - 1);
                })

                alterDiv.find("input[name=image_auto_title]").bind("blur", function (event) {
                    alterDiv.hide();
                    var newValue = alterDiv.find("input[name=image_auto_title]").val();
                    if (newValue.trim().length > 0) {
                        alterDiv.parent().find("label[name=label_sel_auto_title]").text(newValue);
                    }
                })
            },

            buildTitleLabel: function (elementText, elementId, deepIndex) {
                var labelElement = $('<div class="datarow" ><label><input type="radio" name="auto_selected_title" value="' + deepIndex + '" />标题' + deepIndex + '：</label><label name="label_sel_auto_title" bindImage="' + elementId + '"  style="">' + elementText + '</label></div>')
                return labelElement;
            },

            getOptionsEntity: function (key) {
                var self = this;
                return self.options[key];
            },

            getAutoTitleList: function () {
                var self = this;
                var settings = self.getOptionsEntity("settings");
                var tips = self.getOptionsEntity("tips");
                var validate = self.getOptionsEntity("validate");
                var dao = self.getOptionsEntity("dao");
                var config = self.getOptionsEntity("config");

                if (settings.taskid < 0) {
                    tips("error", "参数错误！");
                    return
                }
                var sTime = $.trim($('input[name=sTime]').val()) ,
                    eTime = $.trim($('input[name=eTime]').val());
                if (!validate.checkNum(sTime) || !validate.checkNum(eTime) || settings.taskid < 1) {
                    tips("error", "请填写起点和终点！");
                    return;
                }
                eTime = parseInt(eTime);
                sTime = parseInt(sTime);
                if (eTime <= sTime) {
                    tips("error", "起点应该小于终点！");
                    return;
                }
                if (eTime >= parseInt($("#picNum").text())) {
                    tips("error", "终点尚未加载，请稍后");
                    return;
                }
                var sendData = { start: sTime, end: eTime, from_client: true, key: settings.taskid };
                var newQueryKey = sendData.start + "_" + sendData.end;
                if (self.lastQueryKey == newQueryKey) {
                    self.initContentDiv();

                    return;
                }

                self.dataCenter = [];
                dao.getAutoTitleList(sendData, function (rdata) {
                    if (rdata != null && rdata.code == "A00000") {
                        self.lastQueryKey = newQueryKey;
                        self.getContentDiv().html("");
                        if (rdata.title == null || rdata.title.length < 3) {
                            tips("", "目标区域无可识别标题");
                        } else {
                            var afterDeal = rdata.title.replace(/u('\S+')/g, "$1").replace(/"/g, "\\\"").replace(/'/g, "\"").replace(/\\x([0-9a-f]{2})/g, "\\u00$1")
                            console.log("afterDeal:" + afterDeal);
                            afterDeal = VODCom.TitleFilter.doTitleFilter(afterDeal);
                            var jsonArr = JSON.parse(afterDeal);
                            var tempArr = [];
                            var filterArr = [];

                            var bindDataCenter = [];
                            var index = -1;

                            $.each(jsonArr, function (idx, element) {
                                element.transRange = [];
                                if (element.range != null && element.range.length >= 1) {
                                    element.transRange.push({st: element.range[0], et: element.range[element.range.length - 1] })
                                }
                                index = tempArr.indexOf(element.text)
                                if (index == -1) {
                                    index = tempArr.push(element.text) - 1;
                                    bindDataCenter[index] = { first: element.id, key: element.text, refer: [element], range: [].concat(element.transRange) };
                                    filterArr.push(bindDataCenter[index]);
                                    bindDataCenter[index].deepIndex = filterArr.length;
                                } else {
                                    bindDataCenter[index].refer.push(element);
                                    bindDataCenter[index].range = bindDataCenter[index].range.concat(element.transRange);
                                }
                            })
                            if (filterArr.length > 0) {
                                self.dataCenter = filterArr;
                                self.initContentDiv();
                            }

                        }

                    }
                })
            },
//            saveModifyText: function () {
//                var self = this;
//                var rowArr = self.getContentDiv().find("div.datarow");
//                $.each(rowArr, function (i, elemt) {
//                    self.dataCenter[i].modifyText = $(elemt).find("label[name=label_sel_auto_title]").text()
//                })
//            },
            initContentDiv: function () {
                var self = this;
                self.getContentDiv().html("");
                var stopLength = 5;
                var tips = self.getOptionsEntity("tips");
                if (self.dataCenter.length == 0) {
                    tips("", "目标区域无可识别标题");
                } else {
                    $.each(self.dataCenter.slice(0, stopLength), function (idx, element) {
                        self.buildTitleLabel(element.key, element.first, element.deepIndex).appendTo(self.getContentDiv());
                    });
                    self.getParentDiv().dialog("open");
                }
            },
            doPostEpgAutoTitleData: function (baseObj) {
                var self = this;
                var dao = self.getOptionsEntity("dao");
                var tips = self.getOptionsEntity("tips");

                if (self.AUTO_TITLE_QUERY_FLAG == 1) {
                    var sendData = self.prepareAutoTitleData(baseObj);
                    dao.postAutoTitleData({data: JSON.stringify(sendData) }, function (data) {
                        if (data != null && data.code == "A00000") {
                            tips("success", '投递epg 自动识别标题 数据成功');
                        } else {
                            tips("error", '投递epg 自动识别标题 数据失败');
                        }
                    });
                }
            },
            prepareAutoTitleData: function (baseObj) {
                var self = this;
                var util = self.getOptionsEntity("util");
                var config = self.getOptionsEntity("config");
                var data = {
                    channelName: baseObj.channelName,
                    autoTitle: $.trim(self.AUTO_TITLE_ORIGIN),
                    autoTitleCharLen: 0,
                    addTime: util.formatDateTimeFormat(new Date()),
                    liveBeginTime: baseObj.begin,
                    liveEndTime: baseObj.end,
                    autoFlag: self.AUTO_TITLE_FLAG,
                    user: util.getUserName(),
                    userTitle: $.trim(baseObj.title),
                    userTitleCharLen: 0,
                    legoProgramId: baseObj.programId,
                    percent: 0,
                    titleError: 0,
                    autoTitleStart: -1,
                    autoTitleEnd: -1,
                    userTitleSelect: -1
                };
                data.autoTitleCharLen = Com.string.getStrLength(data.autoTitle);
                data.userTitleCharLen = Com.string.getStrLength(baseObj.title);
                data.percent = VODCom.OCR.accountOcrPercent(data.autoTitle, data.userTitle);
                if (config.OCR_TITLE_FLAG == 1) {
                    data.userTitleSelect = self.USER_TITLE_SELECT;
                    if (!this.checkInRange(data.userTitleSelect)) {
                        data.titleError = 1
                    }
                }
                return data;
            },

            checkInRange: function (userTitleSelect) {
                var checkOver = false;
                var inRange = false;
                $.each(this.dataCenter, function (i, element) {
                    $.each(element.range, function (j, elem) {
                        if (elem.st <= userTitleSelect && userTitleSelect <= elem.et) {
                            checkOver = true;
                            inRange = true;
                            return false;
                        }
                    })
                    if (checkOver) {
                        return false;
                    }
                })
                console.log("userTitleSelect: " + userTitleSelect + ( inRange ? " is " : "isn't" ) + "  in range");
                return inRange
            },

            doCropChange: function (obj) {

            },
            doCropSelect: function (obj) {
                var self = this;
                console.log("doCropSelect " + JSON.stringify(obj));
                if (VODCom.AutoTitle.stopQuery == true) {
                    return;
                }

                var scale = 1;
                var showObj = {
                    x: parseInt(obj.x / scale),
                    y: parseInt(obj.y / scale),
                    w: Math.ceil(obj.w / scale),
                    h: Math.ceil(obj.h / scale)
                };
                console.log("doCropSelect " + JSON.stringify(obj) + "," + JSON.stringify(showObj))
                $("input[name=image_location]").val(JSON.stringify(showObj));
                VODCom.AutoTitle.reqOcrResult(showObj);
            },
            loadDataImage: function (dataIndex) {
                var self = this;
                var data = self.dataCenter[dataIndex].refer[0];
                var imgUrl = data.imagepath;
                var rect = data.rect;
                $("#auto_image_load_text").html("图片加载中....");
                $("#auto_image_load_text_div").show();
                $("#auto_image_load_text_div").hide();
                $("#auto_image").unbind();
                $("#auto_image").bind("load", function (event) {
                    console.log(" auto_image load complete");
                    var newRect = [ rect.x, rect.y , rect.w, rect.h];
                    self.stopQuery = true;
                    self.CropInstance.setSelect([newRect[0], newRect[1], newRect[0] + newRect[2], newRect[1] + newRect[3]  ]);
                    self.stopQuery = false;
                })
                $("#auto_image").attr("src", imgUrl);
                self.CropInstance.setImage(imgUrl);
                console.log("  doMarkOcrImage suc");
            },

            reqOcrResult: function (obj) {
                var self = this;
                var dao = self.getOptionsEntity("dao");
                var tips = self.getOptionsEntity("tips");
                var paramsData = dao.getParamsData();
                var imageName = $("#auto_image").attr("src").split("/").pop()
                var data = {
                    image_name: imageName,
                    channel_code: paramsData.channel_name,
                    from_client: true,
                    key: dao.settings.taskid,
                    x: obj.x,
                    y: obj.y,
                    w: obj.w,
                    h: obj.h
                };
                dao.getOcrResult2(data, function (rData) {
                    console.log("getOcrResult2:" + rData == null ? "" : JSON.stringify(rData));
                    if (rData != null && rData.code == "A00000") {
                        rData.result = rData.result.trim();
                        var alterDiv = $("#auto_title_alterDiv");
                        alterDiv.find("input[name=image_auto_title]").val(rData.result);
                        alterDiv.find("input[name=image_auto_title]").change();
                        if (rData.result.length > 0) {
                            alterDiv.parent().find("label[name=label_sel_auto_title]").text(rData.result);
                        }
                    } else {
                        tips("error", "识别标题失败!");
                    }
                })
            }
        };
    }
);